<template>
  <div class="optimized-image" :style="containerStyle">
    <!-- 加载占位 -->
    <div v-if="loading" class="image-placeholder">
      <el-skeleton-item variant="image" :style="skeletonStyle"/>
    </div>
    
    <!-- 懒加载图片 -->
    <img
      v-show="!loading && !error"
      :src="thumbnailSrc"
      :data-src="src"
      @load="handleLoad"
      @error="handleError"
      :style="imageStyle"
      :alt="alt"
      loading="lazy"
    />
    
    <!-- 错误占位 -->
    <div v-if="error" class="error-placeholder">
      <el-icon><Picture /></el-icon>
      <p>图片加载失败</p>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Picture } from '@element-plus/icons-vue'

const props = defineProps({
  src: String,
  alt: String,
  width: [String, Number],
  height: [String, Number],
  objectFit: {
    type: String,
    default: 'cover'
  }
})

const loading = ref(true)
const error = ref(false)

// 生成缩略图URL
const thumbnailSrc = computed(() => {
  if (!props.src) return ''
  // 如果是远程图片，使用原图
  if (props.src.startsWith('http')) return props.src
  // 本地图片添加缩略图参数
  return `${props.src}?thumbnail=true`
})

const containerStyle = computed(() => ({
  width: typeof props.width === 'number' ? `${props.width}px` : props.width,
  height: typeof props.height === 'number' ? `${props.height}px` : props.height
}))

const imageStyle = computed(() => ({
  objectFit: props.objectFit,
  width: '100%',
  height: '100%'
}))

const skeletonStyle = computed(() => ({
  width: '100%',
  height: '100%'
}))

const handleLoad = () => {
  loading.value = false
}

const handleError = () => {
  loading.value = false
  error.value = true
}

// 图片预加载
onMounted(() => {
  const img = new Image()
  img.src = props.src
})
</script>

<style scoped>
.optimized-image {
  position: relative;
  overflow: hidden;
}

.image-placeholder,
.error-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
}

.error-placeholder {
  color: #909399;
}

.error-placeholder .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.error-placeholder p {
  margin: 0;
  font-size: 12px;
}
</style> 